import 'package:bilibili/http/core/dio_adapter.dart';
import 'package:bilibili/http/core/sun_error.dart';
import 'package:bilibili/http/request/base_request.dart';

import 'sun_net_adapter.dart';

class SunNet {
  // 工厂模式
  factory SunNet() => _getInstance();
  static SunNet get instance => _getInstance();
  static SunNet? _instance;
  SunNet._();
  static SunNet _getInstance() {
    if (_instance == null) {
      _instance = new SunNet._();
    }
    return _instance!;
  }

  Future fire(BaseRequest request) async {
    SunNetResponse? response;
    var error;
    try {
      response = await send(request);
    } on SunNetError catch (e) {
      error = e;
      response = e.data;
      printLog(e.message);
    } catch (e) {
      error = e;
      printLog(e);
    }

    if (response == null) {
      printLog(error);
    }

    var result = response?.data;
    printLog(result);

    var status = response?.statusCode ?? 0;
    switch (status) {
      case 200:
        return result;
      case 401:
        throw NeedLogin();
      case 403:
        throw NeedAuth(result.toString(), data: result);
      default:
        throw SunNetError(status, result.toString(), data: result);
    }
  }

  Future<SunNetResponse<T>> send<T>(BaseRequest request) async {
    SunNetAdapter adapter = new DioAdapter();
    return adapter.send(request);
  }

  void printLog(log) {
    print("sun_net:${log.toString()}");
  }
}
